package com.wuhunyu.service.impl;

import com.wuhunyu.commonutils.check.Check;
import com.wuhunyu.entity.User;
import com.wuhunyu.entity.UserDetail;
import com.wuhunyu.service.PermissionService;
import com.wuhunyu.service.UserService;
import com.wuhunyu.entity.SecurityUser;
import com.wuhunyu.servicebase.exception.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.List;


/**
 * <p>
 * 自定义userDetailsService - 认证用户详情
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 校验参数
        Assert.isRight(Check.isBlank(username), "用户名不能为空");
        // 从数据库中取出用户信息
        User user = userService.selectByUsername(username);
        // 判断用户是否存在
        Assert.isRight(Check.isBlank(user), "用户名不存在");
        // 返回UserDetails实现类
        UserDetail userDetail = new UserDetail();
        BeanUtils.copyProperties(user, userDetail);
        // 查询用户的权限列表
        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        // 校验结果
        Assert.isRight(authorities == null, "查询用户权限列表失败");
        SecurityUser securityUser = new SecurityUser(userDetail);
        securityUser.setPermissionValueList(authorities);
        return securityUser;
    }

}
